import { Body, Controller, Post, Get, UseGuards, Request, Req } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiOperation, ApiProperty, ApiTags } from '@nestjs/swagger';
import { InjectRepository } from '@nestjs/typeorm';
import { UserDemo } from 'src/Entities/UserDemo/UserDemo.dao';
import { Repository } from 'typeorm';
import { JwtService } from "@nestjs/jwt"
import { IsString } from 'class-validator';
//  DTo
export class RegisterDto {

    @ApiProperty()
    @IsString({
        message: '姓名不能为空',
      })
    username: string

    @ApiProperty()
    @IsString()
    password: string
}


//  controllser
@ApiTags("登录接口")
@Controller('')
export class LoginController {

    constructor(
        @InjectRepository(UserDemo) 
        private userDemo: Repository<UserDemo>, 
        
        private jwtService: JwtService
    ) { }

    /**
     * 注册接口 
     * @param body 
     * @returns 
     */
    @Post("register")
    @ApiOperation({ description: "注册接口" })
    async register(@Body() body: RegisterDto) {

        await this.userDemo.save(body)
        return await this.userDemo.findOne({ select: ["username", "password"], where: { username: body.username } })
    }

    /**
     *  登录接口
     * @param req 
     * @param body 
     * @returns 
     */
    @Post("login")
    @ApiOperation({ description: "登录接口" })
    @UseGuards(AuthGuard("local"))
    async login(@Request() req, @Body() body: RegisterDto) {

        return {
            token: this.jwtService.sign(req.user.username)
        }
    }

    /**
     * 测试接口
     * @param req 
     * @returns 
     */
    @Get("getUserInfo")
    @ApiOperation({ description: "获取用户信息" })
    @ApiBearerAuth()
    @UseGuards(AuthGuard("jwt"))
    async getUserInfo(@Req() req) {
        return req.user
    }
}
